<template>
	<view>
		<view class="my-banner">
				<view class="banner-imgs" @touchstart="touchstart" @touchend="touchend" :class="{'on': bannerIndex == index}" v-for="(item, index) in banners"
				 :key="item.id">
					<image :src="item" mode="aspectFill" class="banner-imgs_img"></image>
				</view>
				<view class="banner-dots">
					<view class="banner-dots_item" :class="{'active': bannerIndex == index}" v-for="(item, index) in banners" :key="item.id"></view>
				</view>
			</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				bannerIndex: 0,
				setInter1: null, // 定时器
				startData: { // 滑动数据
					clientX: 0, // 左右滑动
					clientY: 0 // 上下滑动
				},
				banners: [
					'https://s1.ax1x.com/2022/05/31/X8nQqH.png',
					'https://s1.ax1x.com/2022/05/31/X8n8II.png',
					'https://s1.ax1x.com/2022/05/31/X8n3dA.png',
					'https://s1.ax1x.com/2022/05/31/X8nMse.png',
					'https://s1.ax1x.com/2022/05/31/X8n1Zd.png',
				] 
			}
		},

		methods: {
			// 淡入淡出轮播图
			changePic() {
				clearInterval(this.setInter1) // 先将已有的计时器清除
				this.setInter1 = setInterval(function() { // 循环
					this.bannerIndex++
					if (this.bannerIndex == this.banners.length) {
						this.bannerIndex = 0
					}
				}.bind(this), 15000)
			},

			// 滑动开始
			touchstart(e) {
				// console.log('开始位置', e.changedTouches[0].clientX)
				this.startData.clientX = e.changedTouches[0].clientX
				this.startData.clientY = e.changedTouches[0].clientY
			},
			// 滑动结束
			touchend(e) {
				// console.log('结束位置', e.changedTouches[0].clientX)
				const subX = e.changedTouches[0].clientX - this.startData.clientX
				const subY = e.changedTouches[0].clientY - this.startData.clientY
				if (subY > 50 || subY < -50) {
					// console.log('上下滑')
				} else {
					if (subX > 100) { // 右滑，显示前一张，当前的页面减一。如果当前页面是第一张，显示最后一张。
						if (this.bannerIndex == 0) {
							this.bannerIndex = this.banners.length - 1
						} else {
							this.bannerIndex--
						}
						this.changePic()
					} else if (subX < -100) { // 左滑，显示下一张，当前的页面加一。如果当前页面是最后一张，显示第一张。
						if (this.bannerIndex == this.banners.length - 1) {
							this.bannerIndex = 0
						} else {
							this.bannerIndex++
						}
						this.changePic()
					}
				}
			}
		},
		onLoad() {
			this.changePic()
		}

	}
</script>

<style>
	.my-banner {
		width: 100%;
		height:1300rpx;
		position: relative;
	}

	.banner-imgs {
		width: 100%;
		height: 100%;
		opacity: 0;
		transition-duration: 1s;
		/*设置过渡时间*/
		position: absolute;
	}

	.banner-imgs_img {
		position: absolute;
		/*把所有图片放在同一个位置*/
		width: 100%;
		height: 100%;
	}

	.banner-dots {
		position: absolute;
		bottom: 10rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	.banner-dots_item {
		float: left;
		width: 18rpx;
		height: 18rpx;
		border-radius: 50%;
		margin-left: 20rpx;
		background-color: #fff;
	}

	.active {
		background-color: red;
	}

	.on {
		opacity: 1;
	}
</style>

